package com.wfk.h5.service;

import java.math.BigDecimal;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wfk.constant.Constant;
import com.wfk.entity.Account;
import com.wfk.entity.Customer;
import com.wfk.entity.Goods;
import com.wfk.entity.GoodsSpec;
import com.wfk.entity.OrderGoods;
import com.wfk.entity.ReceivedAddr;
import com.wfk.enums.HandleType;
import com.wfk.enums.OrderStatusEnums;
import com.wfk.enums.PayEnums;
import com.wfk.exception.ServiceException;
import com.wfk.service.IAccountService;
import com.wfk.service.ICustomerService;
import com.wfk.service.IGoodsService;
import com.wfk.service.IGoodsSpecService;
import com.wfk.service.IOrderGoodsService;
import com.wfk.service.IReceivedAddrService;
import com.wfk.utils.FunctionUtils;
import com.wfk.utils.MD5Util;
import com.wfk.utils.ResponseData;
import com.wfk.utils.ValidateUtil;

@Service
public class GoodsOrderService {
	@Autowired 
	private IOrderGoodsService orderGoodsService;
	@Autowired
	private IGoodsService goodsService;
	@Autowired
	private IReceivedAddrService receivedAddrService;
	@Autowired
	private ICustomerService customerService;
	@Autowired
	private IGoodsSpecService goodsSpecService;
	@Autowired
	private IAccountService accountService;

	public ResponseData cancelOrder(Integer id){
		OrderGoods order = orderGoodsService.getById(id);
		if(ValidateUtil.objEmpty(order)){
			return ResponseData.baseServiceError("未找到订单记录");
		}else if(!ValidateUtil.isEquals(order.getStatus(),0)){
			return ResponseData.baseServiceError("订单不是已支付不能取消");
		}
		order.setStatus(-1);
		boolean update = this.orderGoodsService.updateById(order);
		return update?ResponseData.ok():ResponseData.baseServiceError("取消订单失败");
	}
	
	public ResponseData handleConfirmRecei(Integer id){
		OrderGoods order = orderGoodsService.getById(id);
		if(ValidateUtil.objEmpty(order)){
			return ResponseData.baseServiceError("未找到订单记录");
		}else if(!ValidateUtil.isEquals(order.getStatus(), 2)){
			return ResponseData.baseServiceError("订单不是待收货状态不能确认收货");
		}
		order.setStatus(3);
		boolean update = this.orderGoodsService.updateById(order);
		if(update){
			Goods goods = goodsService.getById(order.getGoodsCode());
			goods.setSellNumber(goods.getSellNumber()+1);
			boolean goodsUpdate = this.goodsService.updateById(goods);
			if(!goodsUpdate){
				throw new ServiceException("确认收货失败,请稍后重试");
			}
			//XXX 模式
			return ResponseData.ok();
		}
		return ResponseData.baseServiceError("确认收货失败");
	}

	public ResponseData addOrderGoods(String goodsCode,Integer qty,Integer addrid,String payword,Integer spec,boolean falg,String remark,Integer paytype){
		Goods goods =goodsService.getById(goodsCode);
		if(ValidateUtil.objEmpty(goods)){
			return ResponseData.baseServiceError("未找到商品");
		}else if(ValidateUtil.objEmpty(qty)||qty<0){
			return ResponseData.baseServiceError("请选择数量");
		}
		GoodsSpec goodsSpec = this.goodsSpecService.getById(spec);
		if(ValidateUtil.objEmpty(goodsSpec)){
			return ResponseData.baseServiceError("未找到规则");
		}else if(goods.getSpecid()!=goodsSpec.getParent()) {
			return ResponseData.baseServiceError("该规则不属于本商品");
		}
		OrderGoods vo = new OrderGoods();
		BigDecimal payMoney = FunctionUtils.mul(goodsSpec.getMoney(),new BigDecimal(qty), 2);
		if(!falg) {
			ReceivedAddr addr = receivedAddrService.getById(addrid);
			if(ValidateUtil.objEmpty(goods)){
				return ResponseData.baseServiceError("未找到收货地址");
			}else if(!ValidateUtil.empty(PayEnums.getName(paytype))) {
				return ResponseData.baseServiceError("支付方式不支持");
			}
			Customer cus = customerService.getById(addr.getCid());
			if(ValidateUtil.objEmpty(cus)){
				return ResponseData.baseServiceError("用户未注册");
			}
			if(PayEnums.moneypay.getId()==paytype) {
				String pwd = MD5Util.md5Hex(payword);
				if(!ValidateUtil.empty(cus.getPayword())&&!falg){
					return ResponseData.baseServiceError("你还未设置支付密码");
				}else if(!ValidateUtil.equalTo(cus.getPayword(), pwd)){
					return ResponseData.baseServiceError("支付密码错误");
				}
				Account account = this.accountService.get(addr.getCid());
				if(account==null||BigDecimal.ZERO.compareTo(FunctionUtils.sub(account.getMoney(), payMoney,2))>0){
					return ResponseData.baseServiceError("余额不足");
				}
			}
			vo.setCid(addr.getCid());
			vo.setPhone(addr.getPhone());
			vo.setName(addr.getName());
			vo.setAddress(addr.getLocation()+addr.getAddress());
		}
		vo.setOrderid(FunctionUtils.getOrderCode(3, 9));
		vo.setTitle(goods.getTitle());
		vo.setSpecName(goodsSpec.getName());
		vo.setPrice(goodsSpec.getMoney());
		vo.setPaytype(paytype);
		vo.setQty(qty);
		vo.setPaymoney(payMoney);
		vo.setPaycode(FunctionUtils.getOrderCode(3,9));
		vo.setPaytype(paytype);
		vo.setGoodsCode(goods.getGoodsCode());
		vo.setImgurl(goods.getPurl());
		vo.setRemark(remark);
		if(falg) {
			return ResponseData.ok().putDataValue("result", vo);
		}
		
		boolean save = this.orderGoodsService.save(vo);
		if(save) {
			return handleSign(vo);
		}
		return ResponseData.baseServiceError("");
		
	}

	/**
	 * 处理签名
	 * @param order
	 * @param paytype
	 * @return
	 */
	private ResponseData handleSign(OrderGoods order){
		String ordercode =  order.getOrderid();
		BigDecimal money =  order.getPaymoney();
		switch (order.getPaytype()){
		case 1:{//支付宝
			return ResponseData.ok();
		}
		case 2:{//微信
			return ResponseData.ok();
		}
		case 3:{//余额
			return handleCallback(ordercode,"");
		}
		case 4:{//银联
			return ResponseData.ok();
		}
		default:
			return ResponseData.ok();
		}
	}
	
	public ResponseData handleCallback(String ordercode,String transCod){
		OrderGoods orderGoods = this.orderGoodsService.getOrderid(ordercode);
		if(orderGoods==null||!ValidateUtil.isEquals(orderGoods.getStatus(),OrderStatusEnums.not.getId())) {
			return ResponseData.baseServiceError("未找到支付记录或订单已支付");
		}
		//如果是余额支付修改余额
		if(ValidateUtil.isEquals(orderGoods.getPaytype(),PayEnums.moneypay.getId())) {
			String error = accountService.insertAccountDetail(orderGoods.getCid(),HandleType.order.getId(),Constant.pay_out,orderGoods.getPaymoney(),HandleType.order.getName());
			if(ValidateUtil.empty(error)) {
				return ResponseData.baseServiceError(error);
			}
		}
		
		Customer cus = this.customerService.getById(orderGoods.getCid());
		if(!ValidateUtil.isEquals(cus.getIsopen(),1)) {
			cus.setIsopen(Constant.isOpen_success);
			if(this.customerService.updateById(cus)==false) {
				throw new ServiceException("开通扫描失败"); 
			}
		}
		//XXX 模式
		orderGoods.setStatus(OrderStatusEnums.wait.getId());
		orderGoods.setPaytime(new Date());
		boolean updateById = this.orderGoodsService.updateById(orderGoods);
		return updateById?ResponseData.ok():ResponseData.baseServiceError("支付失败请重试");
	}
	
}
